//
//  HomeViewController.swift
//  01MicroBlog
//
//  Created by Apple on 15/7/28.
//  Copyright © 2015年 heima. All rights reserved.
//

import UIKit
import SVProgressHUD

let reuseIdNormal = "reuseIdNormal"
let reuseIdForward = "reuseIdForward"

class HomeViewController: BaseTableViewController {
    
    var statuses: [Status]? {
        didSet {
            tableView.reloadData()
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if UserAccount.userLogon == false {
            loginView?.setUpInformation(true, imageName: "visitordiscover_feed_image_smallicon", introText: "关注一些人，回这里看看有什么惊喜")
            return
        }
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "selectPicture:", name: WJStatusPictureViewSelectPictureNotificationName, object: nil)
        
        prepareForTableView()
        
        loadDataList()
        
    }
    
    // MARK: - 接收通知，回调的方法
    @objc private func selectPicture(n:NSNotification) {
        
        guard let urls = n.userInfo![StatusPictureViewSelectPictureURLsKey] as? [NSURL] else {
            print("URL数组不存在")
            return
        }
        
        guard let indexPath = n.userInfo![StatusPictureViewSelectPictureIndexPathKey] else {
            print("选中图片不存在")
            return
        }
        
        guard let pic = n.object as? StatusPictureView else {
            print("传的参数有误")
            return
        }
        
        // 记录下穿过来的对象
        pictureView = pic
        indexP = indexPath as? NSIndexPath
        largeUrls = urls
        presentedView.sd_setImageWithURL(largeUrls![indexP!.row] as! NSURL)
        
        let vc = PictureBrowserController(pictURLs: urls, indexPath: indexPath as! NSIndexPath)
        
        vc.transitioningDelegate = self
        
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        presentViewController(vc, animated: true, completion: nil)
    }
    
    private func prepareForTableView() {
        
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: reuseIdNormal)
        tableView.registerClass(StatusForwardCell.self, forCellReuseIdentifier: reuseIdForward)
        
        tableView.estimatedRowHeight = 200
        
        refreshControl = WJRefreshControl()
        refreshControl?.addTarget(self, action: "loadDataList", forControlEvents: UIControlEvents.ValueChanged)

    }
    
    // 上拉刷新出现重复的微博
    // 上拉刷新 UICollectionViewFlowLayout 的itemSize超过 UICollectionView 的边界

/// 加载数据
    // 上拉刷新标识
    var pullUpFlag:Bool = false
     func loadDataList() {
        
        refreshControl?.beginRefreshing()
        
        var since_id = self.statuses?.first?.id ?? 0
        var max_id = 0
        
        // 上拉刷新
        if pullUpFlag == true {
            since_id = 0
            max_id = statuses?.last?.id ?? 0
            pullUpFlag = false
        }
        
        Status.loadStatusDataList(since_id, max_id:max_id) { (dataList, error) -> () in
            
            self.refreshControl!.endRefreshing()
            
            if error != nil {
                SVProgressHUD.showErrorWithStatus("不给力")
                return
            }
            
            let count = dataList?.count
            print("刷新了\(count)条微博")
            
            
            if since_id > 0 {
                self.showupTipLabel(count!)
            }
            
            if count == 0 {
                return
            }
            
            // 下拉刷新
            if since_id > 0 {
                self.statuses = dataList! + self.statuses!
            } else if max_id > 0 {
                self.statuses = self.statuses! + dataList!
            } else {
                self.statuses = dataList!
            }
 
        }
    }
    
    private func showupTipLabel(count:Int) {
        tipLabel.text = (count == 0) ?  "暂时没有新的微博" : "刷新到\(count)条微博"
        let rect = tipLabel.frame
        
        UIView.animateWithDuration(1.0, animations: { () -> Void in
            
            // 设置自动反弹
            UIView.setAnimationRepeatAutoreverses(true)
            
            self.tipLabel.frame = CGRectOffset(rect, 0, 3 * rect.size.height)
            }) { (_) -> Void in
                // 将标签复位
                self.tipLabel.frame = rect
        }
    }

    
    // MARK: - 数据源方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let _ = statuses {
            return (statuses?.count)!
        }
        return 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let status = statuses?[indexPath.row]
        var cell:StatusCell
        
        if status?.retweeted_status != nil {
           cell = tableView.dequeueReusableCellWithIdentifier(reuseIdForward, forIndexPath: indexPath) as! StatusForwardCell

        } else {
            cell = tableView.dequeueReusableCellWithIdentifier(reuseIdNormal, forIndexPath: indexPath) as! StatusNormalCell
        }
        
        cell.status = status
        
        // 滚到了最后，刷新早期的微博
        if indexPath.row == statuses!.count - 1 {
            pullUpFlag = true
            loadDataList()
        }
        
        return cell

    }

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let status = statuses?[indexPath.row]
        if status?.rowHeight != nil {
            return (status?.rowHeight)!
        }
        
        var cell:StatusCell
        if status?.retweeted_status != nil {
            // 注意，这里不能用indexPath（会调用行高方法）方式取！ 否则会造成死循环！
            cell = tableView.dequeueReusableCellWithIdentifier(reuseIdForward) as! StatusForwardCell
        } else {

            cell = tableView.dequeueReusableCellWithIdentifier(reuseIdNormal) as! StatusNormalCell
        }
        status?.rowHeight = cell.getRowHeight(status!)

        return (status?.rowHeight)!

    }
    
    // MARK: - 懒加载控件
    private lazy var tipLabel:UILabel = {
        let h: CGFloat = 44
        let label = UILabel(frame: CGRect(x: 0, y: -2 * h, width: self.view.bounds.width, height: h))
        
        label.backgroundColor = UIColor.orangeColor()
        label.textColor = UIColor.redColor()
        label.textAlignment = NSTextAlignment.Center

        // 将label加到navigationBar上面，保证label不会随着tableView的滚动而滚动
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        
        return label
    }()
    
    // 记录下传过来的视图
    private var pictureView:StatusPictureView?
    
    // 要展示的视图
    private lazy var presentedView:UIImageView = {
        
        let presentedView = UIImageView()
        presentedView.contentMode = UIViewContentMode.ScaleAspectFill
        presentedView.clipsToBounds = true
        
        return presentedView
    }()
    
    private var indexP:NSIndexPath?
    private var largeUrls:[NSURL]?
}

// MARK: - 让控制器遵守转场协议 UIViewControllerTransitioningDelegate
extension HomeViewController: UIViewControllerTransitioningDelegate {
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = true
        return self
    }
    
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = false
        return self
    }
}

var isPresented:Bool = false

extension HomeViewController:UIViewControllerAnimatedTransitioning {

    // 设置动画时长
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.5
    }
  
    // 设置转场动画方式
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        
//        let fromVc = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
//        let toVc = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
//        print(fromVc)
//        print(toVc)
        let beginRect = self.pictureView!.cellScreenFrame(self.indexP!)
        let endRect = self.pictureView!.cellFullScreenFrame(self.indexP!)
        presentedView.frame = beginRect
        
        // modal 出来方式
        if isPresented {

            // 加入替身视图
            transitionContext.containerView()?.addSubview(presentedView)
            
            // 呈现动画
            UIView.animateWithDuration(1.0, animations: { () -> Void in
                
                self.presentedView.frame = endRect

                }) { (_) -> Void in
                    
                    // 动画执行结束后，移除替身视图，在containerView中加入实际视图
                    self.presentedView.removeFromSuperview()
                    let toView = transitionContext.viewForKey(UITransitionContextToViewKey)
                    transitionContext.containerView()?.addSubview(toView!)
                    transitionContext.completeTransition(true)
            }
            
        } else {
            
            let fromVc = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as! PictureBrowserController
            let indexPath = fromVc.currentIndexPath()
            
            let rect = pictureView!.cellScreenFrame(indexPath)
            
            let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
            
            let iv = fromVc.currentImageView()
            
//            print("iv--\(iv.transform)")
//            print("fromView--\(fromView)")
            
            // 设置图像视图的位置
            iv.center = fromView.center
            // `累加`父视图的形变
            let scale = fromView.transform.a
            iv.transform = CGAffineTransformScale(iv.transform, scale, scale)
            
//            print("iv ====== \(iv.transform)")
//
            // 将当前图像视图，添加到容器视图
            transitionContext.containerView()?.addSubview(iv)
//
            // 将 fromView 从容器视图中移出
            fromView.removeFromSuperview()

            transitionContext.containerView()?.addSubview(fromView)

            // 呈现动画
            UIView.animateWithDuration(1.0, animations: { () -> Void in
                
                iv.frame = rect

                }) { (_ ) -> Void in
                    // 动画结束，删除
                    iv.removeFromSuperview()
                    transitionContext.completeTransition(true)
            }

        }
        
        
    }
}

